import Mock from 'mockjs'
import { ResultEnum } from '@/utils/enums/http-enum'

// 请求成功
export function resultSuccess(
  {
    result = null as any,
    message = 'ok',
  }
) {
  return Mock.mock({
    code: ResultEnum.SUCCESS,
    result,
    message,
    type: 'success',
  })
}

// 请求失败
export function resultError(
  {
    code = ResultEnum.ERROR,
    result = null,
    message = 'Request failed',
  }
) {
  return {
    code,
    result,
    message,
    type: 'error',
  }
}

// 对数据进行分页
export function handlePageData<T = any>(pageNo: number, pageSize: number, array: T[]): T[] {
  const offset = (pageNo - 1) * pageSize
  return offset + pageSize >= array.length ?
    array.slice(offset, array.length) :
    array.slice(offset, offset + pageSize)
}

// 获取列表数据
export function resultPage(
  {
    currentPage = 1,
    pageSize = 10,
    list = [],
  }
) {
  const pageData = handlePageData(currentPage, pageSize, list)

  return {
    currentPage,
    pageSize,
    total: list.length,
    list: pageData,
  }
}

/**
 * @param {Number} times 回调函数需要执行的次数
 * @param {Function} callback 回调函数
 */
export function doCustomTimes(times: number, callback: any) {
  let i = -1
  while (++i < times) {
    callback(i)
  }
}

export interface requestParams {
  method: string,
  body: any,
  headers: {
    Authorization?: string,
    [k: string]: any,
  },
  query: any,
}

/**
 * @description 本函数用于从 request 数据中获取token，请根据项目的实际情况修改
 *
 */
export function getRequestToken({ headers }: requestParams): string | undefined {
  const authenticationScheme = 'Bearer'
  const { authorization } = headers
  return (authorization || '').slice(authenticationScheme.length + 1)
}
